import { request } from "../../request/index";

// pages/goods_detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailObj: {},
    isCollect: false
  },

  goodsInfo: {},


  //获取商品详情数据
  async getGoodsDetail(goods_id) {
    const res = await request({ url: "/goods/detail", data: { goods_id } });
    this.goodsInfo = res;
    //获取缓存中商品收藏的数据
    let collect = wx.getStorageSync("collect") || [];
    let isCollect = collect.some(v => v.goods_id === this.goodsInfo.goods_id);
    this.setData({
      detailObj: {
        goods_id: res.goods_id,
        goods_name: res.goods_name,
        goods_price: res.goods_price,
        goods_introduce: res.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: res.pics
      },
      isCollect
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    let options = pages[pages.length - 1].options;
    const { goods_id } = options;
    // console.log(goods_id);
    this.getGoodsDetail(goods_id);
  },

  //点击收藏
  handleTapCollect() {
    //获取缓存中商品收藏的数据
    let collect = wx.getStorageSync("collect") || [];
    let index = collect.findIndex(v => v.goods_id === this.goodsInfo.goods_id);
    if (index === -1) {
      collect.push(this.goodsInfo);
      wx.showToast({
        title: "收藏成功",
        mask: true
      })
    } else {
      collect.splice(index, 1);
      wx.showToast({
        title: "取消收藏",
        mask: true
      })
    }
    this.setData({
      isCollect: !this.data.isCollect
    })
    wx.setStorageSync("collect", collect);

  },

  //点击轮播图预览
  handlePreviewImage(e) {
    // console.log("预览");
    const urls = this.goodsInfo.pics.map(v => v.pics_mid);
    let { url } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls
    })
  },
  //加入购物车
  handleToCart() {
    // console.log("加入");
    let cart = wx.getStorageSync("cart") || [];
    let index = cart.findIndex(v => v.goods_id === this.goodsInfo.goods_id)
    if (index === -1) {
      //不存在相同商品
      this.goodsInfo.goods_num = 1;
      this.goodsInfo.checked = true;
      cart.push(this.goodsInfo)
    } else {
      cart[index].goods_num++;
    }
    //把购物车重新添加到缓存
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '添加成功~',
      icon: 'success',
      image: '',
      duration: 1500,
      mask: true,
    });
  },

  //立即购买
  handleBuy() {
    const address = wx.getStorageSync("address");
    let quickBuy = [];
    quickBuy.push(this.goodsInfo);
    if (Object.keys(address).length === 0) {
      wx.switchTab({
        url: '/pages/cart/index',
      })
    } else {
      wx.setStorageSync("quickBuy", quickBuy);
      wx.navigateTo({
        url: '/pages/pay/index?buy=1',
      });
    }
  }

})